package com.ds.api.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ds.api.biz.UserServiceBiz;
import com.ds.api.dao.SendMessageLogMapper;
import com.ds.api.dao.TypeVerifyMapper;
import com.ds.api.dao.UserAllskillMapper;
import com.ds.api.dao.UserBasicInfoMapper;
import com.ds.api.dao.UserKeyMapper;
import com.ds.api.dao.UserLoginThirdTokensMapper;
import com.ds.api.dao.UserWalletMapper;
import com.ds.api.model.TypeVerify;
import com.ds.api.model.UserBasicInfo;
import com.ds.api.model.UserKey;
import com.ds.api.model.UserLoginThirdTokens;
import com.ds.api.model.UserWallet;
import com.ds.api.utils.FtpUploadUtil;
import com.ds.api.utils.MD5;
import com.ds.api.utils.Utils;
import com.google.gson.Gson;

/**
 * 注册接口
 * @author xiangwei
 *
 */
@RestController
@RequestMapping("/user")
public class RegisterController extends BaseController {

	private static final Logger log = LoggerFactory
			.getLogger(RegisterController.class);
	@Autowired
	private SendMessageLogMapper logmapper;

	@Autowired
	private UserBasicInfoMapper userMapper;

	@Autowired
	private UserServiceBiz biz;

	@Autowired
	private UserLoginThirdTokensMapper tokensMapper ;

	@Autowired
	private UserKeyMapper keymapper;
	
	@Autowired
	private UserWalletMapper walletMapper;
	
	@Autowired
	private UserAllskillMapper skillMapper;
	
	@Autowired
	private TypeVerifyMapper verifMapper;
	
	/**
	 * 用户注册
	 * @param param
	 * @param info
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/register")
	public  void registerUser(@RequestParam Map<String,String> param, UserBasicInfo info,
			HttpServletRequest request, HttpServletResponse response) {

		String resultStr="0";
		Map<String, Object> result = new HashMap<String, Object>();
		if(checkTime(param)>0) {
			//判断用户名是否存在
			param.put("userpwd", null);
			List<UserBasicInfo> baseInfo=userMapper.query(param);
			if(baseInfo.size()>0){
				resultStr="1";
				result.put("err_str","用户名已经存在");
			}else{
				info.setUserpwd(MD5.getMD5Encode(info.getUserpwd()));
				info.setUsercredit(50);//默认给50的信誉值
				userMapper.insert(info);

				List<UserBasicInfo> userinfo=userMapper.query(param);

				UserBasicInfo base=userinfo.get(0);
				//查询需要的字段 封装到Map上
				result.put("key",biz.insertUserKey(base.getUid()));
			}
		}else {
			resultStr="1";
			result.put("err_str","验证码失败");
		}
		result.put("result",resultStr);
		Gson gson = new Gson();
		try {
			response.setCharacterEncoding("utf-8");
			response.getWriter().println(gson.toJson(result));
		} catch (Exception e) {
			log.info("注册出错："+e);
		}

	}

	/**
	 * 验证用户名是否存在
	 */
	@RequestMapping(value = "/checkUser")
	public  void checkUser(@RequestParam Map<String,String> param,
			HttpServletRequest request, HttpServletResponse response) {

		String resultStr="0";
		Map<String, Object> result = new HashMap<String, Object>();
		//判断用户名是否存在
		List<UserBasicInfo> baseInfo=userMapper.query(param);
		if(baseInfo.size()>0){
			resultStr="1";
			result.put("err_str","用户名已经存在");
		}
		result.put("result",resultStr);
		Gson gson = new Gson();
		try {
			response.setCharacterEncoding("utf-8");
			response.getWriter().println(gson.toJson(result));

		} catch (Exception e) {
			log.info("程序出错："+e);
		}

	}


	/**
	 * 用户登录
	 * @param param
	 * @param info
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/login")
	public  void login(@RequestParam Map<String,String> param,
			HttpServletRequest request, HttpServletResponse response) {
		String resultStr="0";
		Map<String, Object> result = new HashMap<String, Object>();
		//为空代表普通登录
		if(null==param.get("type")||"".equals(param.get("type"))) {
			param.put("userpwd",MD5.getMD5Encode(param.get("userpwd")));
			List<UserBasicInfo> userinfo=userMapper.query(param);
			if(userinfo.size()>0) {
				UserBasicInfo base=userinfo.get(0);
				base.setUserpwd("");
				//查询需要的字段 封装到Map上
				result.put("userBaseInfo", userinfo.get(0));//用户基本信息
				result.put("key",biz.insertUserKey(base.getUid()));
			}else{
				resultStr="1";
				result.put("err_str","用户名或密码错误");
			}
		}
		result.put("result",resultStr);
		response.setCharacterEncoding("utf-8");
		Gson gson = new Gson();
		try {
			response.getWriter().println(gson.toJson(result));
		} catch (Exception e) {
			log.info("程序出错："+e);
		}

	}

	/**
	 * 忘记密码
	 */
	@RequestMapping(value = "/forget")
	public  void forget(@RequestParam Map<String,String> param, UserBasicInfo info,
			HttpServletRequest request, HttpServletResponse response) {
		String resultStr="0";
		Map<String,String>map=new HashMap<String,String>();
		map.put("username",info.getMobilephone() );
		//	    http://localhost:8080/ds_api/user/forget?userpwd=123456&validateCode=2335&mobilephone=18516000540
		int  count=logmapper.checkTime(param);
		Map<String, Object> result = new HashMap<String, Object>();
		if(count>0) {//验证码通过后

			List<UserBasicInfo> baseInfo=userMapper.query(map);//根据用户名取值
			if(baseInfo.size()>0){
				info.setUid(baseInfo.get(0).getUid());
				info.setUserpwd(MD5.getMD5Encode(info.getUserpwd()));
				userMapper.updateByPrimaryKeySelective(info);
			}else{
				resultStr="1";
				result.put("err_str","手机号码不存在");
			}
		}else {
			resultStr="1";
			result.put("err_str","验证码失败");
		}
		result.put("result",resultStr);
		Gson gson = new Gson();
		try {
			response.setCharacterEncoding("utf-8");
			response.getWriter().println(gson.toJson(result));
		} catch (Exception e) {
			log.info("程序出错："+e);
		}

	}

	/**
	 * thirdlogin第三方登录
	 */
	@RequestMapping(value = "/thirdLogin")
	public  void thirdLogin(@RequestParam Map<String,String> param,
			HttpServletRequest request, HttpServletResponse response) {
		String resultStr="0";
		String openid=param.get("openid");
		String access_token=param.get("access_token");
		String expires_in=param.get("expires_in");
		String headimgurl=param.get("headimgurl");
		String nickname=param.get("nickname");
		String refresh_token=param.get("refresh_token");
		UserBasicInfo info=null;

		UserLoginThirdTokens user=new UserLoginThirdTokens();
		Map<String, Object> result = new HashMap<String, Object>();
		//为空QQ登录
		if(null==refresh_token||"".equals(refresh_token)) {
			user.setQqOpenid(openid);
			user.setQqAccessToken(access_token);
			user.setQqExpiresIn(expires_in);

//			key.setQqOpenId(openid);
		}else {
//			key.setWxOpenId(openid);
		    user.setWxExpiresIn(expires_in);
			user.setWxOpenid(openid);
			user.setWxRefreshToken(refresh_token);
			user.setWxAccessToken(access_token);
		}
		user.setNickName(nickname);
		user.setHeadimgurl(headimgurl);
		List<UserLoginThirdTokens> queryUsers=tokensMapper.query(user);
		if(queryUsers.size()>0) {
			user.setUid(queryUsers.get(0).getUid());
			if(queryUsers.get(0).getFkUserBasicinfoUid()!=null&&!"".equals(queryUsers.get(0).getFkUserBasicinfoUid())) {
				UserKey userkey=new UserKey();
				userkey.setFkUserBaseinfoId(queryUsers.get(0).getFkUserBasicinfoUid());
				List<UserKey> lists=keymapper.query(userkey);
				if(lists.size()>0) {
					String uuid=UserServiceBiz.getUuid();
					userkey.setId(lists.get(0).getId());
					userkey.setUidKey(uuid);
					userkey.setIsActive("0");
					userkey.setUpdateTime(new Date());
					keymapper.updateByPrimaryKeySelective(userkey);
					result.put("key",uuid);
				}
//				UserBasicInfo userInfo=userMapper.selectByPrimaryKey(queryUsers.get(0).getFkUserBasicinfoUid());
//				userInfo.setHeadimgurl(headimgurl);
//				userInfo.setNicename(nickname);
//				userMapper.updateByPrimaryKeySelective(userInfo);
			}
			tokensMapper.updateByPrimaryKeySelective(user);
		}else {
			tokensMapper.insert(user);
		}
		result.put("result",resultStr);
		result.put("uid", user.getUid());
		result.put("mobilephone", user.getPhone()==null?"":user.getPhone());
		response.setCharacterEncoding("utf-8");
		Gson gson = new Gson();
		try {
			response.getWriter().println(gson.toJson(result));
		} catch (Exception e) {
			log.info("程序出错："+e);
		}

	}
	
	/**
	 * 第三方注册
	 */
	/**
	 * thirdlogin第三方登录
	 */
	@RequestMapping(value = "/thirdRegister")
	public  void thirdRegister(@RequestParam Map<String,String> param,
			HttpServletRequest request, HttpServletResponse response) {
		String resultStr="0";
		String phone=param.get("mobilephone");
	    String uid=param.get("uid");

		UserBasicInfo baseInfo=null;
		Map<String, Object> result = new HashMap<String, Object>();
		if(checkTime(param)>0) {
			UserLoginThirdTokens tokens=tokensMapper.selectByPrimaryKey(Integer.parseInt(uid));
			param.put("username", phone);
			List<UserBasicInfo> baseInfos=userMapper.query(param);
			if(baseInfos.size()>0) {
				baseInfo=baseInfos.get(0);
//				if(baseInfo.getNicename()==null) {
//					baseInfo.setNicename(tokens.getNickName());
//				}
//				if(baseInfo.getHeadimgurl()==null) {
//					baseInfo.setHeadimgurl(tokens.getHeadimgurl());
//				}
//                userMapper.updateByPrimaryKeySelective(baseInfo);
			}else {
				baseInfo=new UserBasicInfo(); 
				baseInfo.setNicename(tokens.getNickName());
				baseInfo.setHeadimgurl(tokens.getHeadimgurl());
				baseInfo.setMobilephone(phone);
				baseInfo.setUsercredit(50);
				userMapper.insert(baseInfo);
			}
			tokens.setFkUserBasicinfoUid(baseInfo.getUid());
			tokensMapper.updateByPrimaryKeySelective(tokens);
			result.put("key",biz.insertUserKey(baseInfo.getUid()));
		}else {
			resultStr="1";
			result.put("err_str","验证码失败");
		}
		result.put("result",resultStr);
		Gson gson = new Gson();
		try {
			response.setCharacterEncoding("utf-8");
			response.getWriter().println(gson.toJson(result));
		} catch (Exception e) {
			log.info("程序出错："+e);
		}
	}
	
	
	/**
	 * 判断验证码是否有效
	 */
	public int checkTime(Map<String,String> param) {
		int  count=logmapper.checkTime(param);
		return count;
	}
	
	/**
	 * 通过key拿用户
	 * @param param
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/get")
	public  void get(@RequestParam Map<String,Object> param,
			HttpServletRequest request, HttpServletResponse response) {
		String resultStr="0";
		Map<String, Object> result = new HashMap<String, Object>();

		Integer userId=Integer.parseInt(request.getAttribute("USER_ID")+"");
		UserBasicInfo info=userMapper.selectByPrimaryKey(userId) ;
		TypeVerify vertype=null;
		param.put("userId",userId);
		if(info.getHeadimgurl()==null||"".equals(info.getHeadimgurl())){
		    UserLoginThirdTokens user=new UserLoginThirdTokens();
		    user.setFkUserBasicinfoUid(userId);
		    List<UserLoginThirdTokens> lists=tokensMapper.query(user);
		    if(lists.size()>0){
	            info.setHeadimgurl(lists.get(0).getHeadimgurl());
	            info.setNicename(lists.get(0).getNickName());
		    }
//		    info.setHeadimgurl("https://119.29.119.28/1.jpg");
		}
		info.setVipName(Utils.callTypeMap.get(info.getVipId()));
		if(info.getVipName()==null){
		    info.setVipName("成员");
		}
		List<UserWallet> wallet=  walletMapper.query(param);
		if(wallet.size()>0){
		      result.put("wallet", wallet.get(0));
		}else {
		      result.put("wallet", "");
		}
		List<Map<String,Object>> skill=skillMapper.query(param);
		if(skill.size()>0){
              result.put("skill", skill);
        }else {
		      result.put("skill", "");
        }
		List<TypeVerify> verifys=verifMapper.query(param);
		if(verifys.size()>0){
		    List<String> list=new ArrayList<String>();
		    for (TypeVerify type : verifys) {
		        list.add(type.getOppType());
            }
//		    vertype=new TypeVerify();
//		    vertype.setVerifyType(verifys.get(0).getVerifyType());
//	        vertype.setStatus(verifys.get(0).getStatus());
            result.put("typeVerify", verifys);
            result.put("opp_type", list);

		}else {
		      result.put("typeVerify", "");
		}
		info.setUserpwd(null);
		result.put("userInfo", info);
		result.put("result",resultStr);
		response.setCharacterEncoding("utf-8");
		Gson gson = new Gson();
		try {
			response.getWriter().println(gson.toJson(result));
		} catch (Exception e) {
			log.info("id不存在："+e);
		}
	}
	
	/**
	 * 修改用户接口
	 */
	@RequestMapping(value = "/update")
	public  void update(@RequestParam Map<String,String> param,
			HttpServletRequest request, HttpServletResponse response) {
		String resultStr="0";
		Map<String, Object> result = new HashMap<String, Object>();

		Integer userId=Integer.parseInt(request.getAttribute("USER_ID")+"");
		UserBasicInfo info=userMapper.selectByPrimaryKey(userId) ;
		UserBasicInfo updateInfo=new UserBasicInfo();
		updateInfo.setUid(info.getUid());
		String headimgurl=param.get("headimgurl");//头像
		if(headimgurl!=null&&!"".equals(headimgurl)) {
			String path="/opt/img/image/";
			String imagepath=new Date().getTime()+".png";
			File file=FtpUploadUtil.GenerateImage(headimgurl,path+imagepath);
			if(file!=null) {
				updateInfo.setHeadimgurl("https://www.dsxie8888.com/"+imagepath);
			}
		}
		String nicename=param.get("nicename");
		if(nicename!=null&&!"".equals(nicename)) {
			updateInfo.setNicename(nicename);
		}
		String userpwd=param.get("userpwd");
		String userpwdNew=param.get("userpwdNew");
		if(userpwd!=null&&!"".equals(userpwd)) {
			if(!MD5.getMD5Encode(userpwd).equals(info.getUserpwd())) {
				result.put("result","1");
		        result.put("err_str","原密码修改不正确");
			}else {
				updateInfo.setUserpwd(MD5.getMD5Encode(userpwdNew));
			}
		}
		if("0".equals(resultStr)) {
			userMapper.updateByPrimaryKeySelective(updateInfo);
		}
		result.put("result",resultStr);
		response.setCharacterEncoding("utf-8");
		Gson gson = new Gson();
		try {
			response.getWriter().println(gson.toJson(result));
		} catch (Exception e) {
			log.info("id不存在："+e);
		}
	}
	
	/**
     * 查询供应商
     */
    @RequestMapping(value = "/search")
    public  void search(@RequestParam Map<String,Object> param,
            HttpServletRequest request, HttpServletResponse response) {
        List<Integer> lists=new ArrayList<Integer>();
        String resultStr="0";
        String opp_type=param.get("opp_type")+"";
        if(opp_type!=null&&!"".equals(opp_type)) {
            String []fkparentIds=opp_type.split(",");
            for (String string : fkparentIds) {
                lists.add(Integer.parseInt(string));
            }
        }      
        param.put("oppType", lists);

        Map<String, Object> result = new HashMap<String, Object>();

        List<UserBasicInfo> userinfo=userMapper.searchUser(param);
        

        //查询需要的字段 封装到Map上
        result.put("result",resultStr);
        result.put("data", userinfo);
        Gson gson = new Gson();
        try {
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(gson.toJson(result));
        } catch (Exception e) {
            log.info("注册出错："+e);
        }


    }
}
